import 'package:flutter/material.dart';

///
/// des: 动画列表 AnimatedList
///
class AnimatedListDemo extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _AnimatedListDemo();
}

class _AnimatedListDemo extends State<AnimatedListDemo> with SingleTickerProviderStateMixin {
  // 列表数据
  List<int> _list = [];
  // 列表控制器
  final GlobalKey<AnimatedListState> _listKey = GlobalKey<AnimatedListState>(); // GlobalKey 用于获取列表控制器

  /// 初始化数据
  void _addItem() {
    final int _index = _list.length; // final 修饰的变量只能赋值一次
    _list.insert(_index, _index);
    _listKey.currentState.insertItem(_index);
  }
  /// 移除数据
  void _removeItem() {
    final int _index = _list.length - 1;
    var item = _list[_index].toString();
    _listKey.currentState.removeItem(_index, (context, animation) => _buildItem(item, animation));
    _list.removeAt(_index);
  }
  /// 构建列表项
  Widget _buildItem(String _item, Animation _animation) {
//    return SlideTransition(
//      position: _animation.drive(CurveTween(curve: Curves.easeIn)).drive(Tween<Offset>(begin: Offset(1,1),end: Offset(0,1))),
//      child: Card(
//        child: ListTile(
//          title: Text(
//            _item,
//          ),
//        ),
//      ),
//    );
    return SizeTransition( // SizeTransition 用于控制子组件的大小
      sizeFactor: _animation, // sizeFactor 用于控制子组件的大小 0.0-1.0
      child: Card( // Card 用于包裹列表项
        child: ListTile( // ListTile 用于构建列表项
          title: Text(
            _item,
          ),
        ),
      ),
    );
  }

  /// 构建界面
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: AnimatedList(
        key: _listKey,
        initialItemCount: _list.length,
        itemBuilder: (BuildContext context, int index, Animation animation) {
          return _buildItem(_list[index].toString(), animation);
        },
      ),
      floatingActionButton: Row( // Row 用于横向排列子组件
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          FloatingActionButton(
            onPressed: () => _addItem(),
            child: Icon(Icons.add),
          ),
          SizedBox(
            width: 60,
          ),
          FloatingActionButton(
            onPressed: () => _removeItem(),
            child: Icon(Icons.remove),
          ),
        ],
      ),
    );
  }
}
